package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.context.BaseContext;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果访问的是静态资源，那么直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //接下来就不是静态资源的拦截
        try {
            //1 从请求头中获取令牌
            String token = request.getHeader(jwtProperties.getUserTokenName());
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId=Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前微信账户为:{}",userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (NumberFormatException e) {
            //不通过，还回状态码
            response.setStatus(401);
            return false;
        }
    }
}
